package com.dayuanit.booksystem.v3.net;

import com.dayuanit.booksystem.v3.net.common.DypRequest;
import com.dayuanit.booksystem.v3.util.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 解析DYP协议
 */
public class DypAnalysis {

    public DypRequest analysis(String message) {
        if (StringUtils.isBlank(message)) {
            throw new TomdogException("协议解析失败");
        }

        if (-1 == message.indexOf("$")) {
            throw new TomdogException("协议格式错误");
        }

        //请求的格式：功能编号$参数k=参数value&参数key=参数value&....
        String[] msgArray = message.split("\\$");

        String funtionNumber = msgArray[0];
        String params = msgArray[1];
        //[k=v,  k=v,  k=v]
        String[] paramsInfoArrays = params.split("&");

        Map<String, String> paramMap = new HashMap<>();
        for (String paramInfo : paramsInfoArrays) {
            //paramInfo-> k=v
            String[] kv = paramInfo.split("=");
            paramMap.put(kv[0], kv[1]);
        }

        DypRequest dypRequest = new DypServletRequest(Integer.parseInt(msgArray[0]), paramMap);
        return dypRequest;
    }

    public static void main(String[] args) {
        String msg[] = {"a", "b", "c", "d"};
        String[] strings = Arrays.copyOfRange(msg, 1, msg.length);
        System.out.println(Arrays.toString(strings));
    }
}
